package com.ego.service.impl;

import com.ego.dubbo.service.ItemCatDubboService;
import com.ego.pojo.ItemCat;
import com.ego.pojo.NavMenu;
import com.ego.pojo.NavNode;
import com.ego.service.ItemService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @DubboReference
    private ItemCatDubboService itemCatDubboService;

    @Override
    @Cacheable(cacheNames = "com.ego",key = "'nav'")
    public NavMenu showNav() {
        NavMenu navMenu = new NavMenu();
        List<Object> data = selectChildrenByParentId(0L);
        navMenu.setData(data);
        return navMenu;
    }

    public List<Object> selectChildrenByParentId(long parentId) {
        List<ItemCat> itemCats = itemCatDubboService.selectItemCatByParentId(parentId);
        List<Object> data = new ArrayList<>();
        for (ItemCat itemCat : itemCats) {
            if (itemCat.getIsParent()) {
                NavNode navNode = new NavNode();
                navNode.setU("/products/" + itemCat.getId() + ".html");
                navNode.setN("<a href='/products/" + itemCat.getId() + ".html'>" + itemCat.getName() + "</a>");
                navNode.setI(selectChildrenByParentId(itemCat.getId()));
                data.add(navNode);
            } else {
                data.add("/products" + itemCat.getId() + ".html|" + itemCat.getName());
            }
        }
        return data;
    }
}
